package benchmark

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	"runtime/debug"
	"strconv"
	"strings"
	"test/unit_function/bean"
	"test/unit_function/unique_snowflake"
	"time"
)

func ParseToBenchmarkBean(fileName string, refTestId int64) []bean.BenchmarkEntity {
	// 读取文件的每一行，
	file, err := os.Open(fileName)
	if err != nil {
		fmt.Println("Error opening file:", err)
		return nil
	}
	defer file.Close()
	// 编译正则表达式
	pattern := `^([\S]+)[^0-9]+([0-9,.]+)[^0-9]+([0-9|.]+)[^0-9]+([0-9|.]+).*`
	re, err := regexp.Compile(pattern)
	if err != nil {
		fmt.Println("Invalid regex:", err)
		return nil
	}
	scanner := bufio.NewScanner(file)
	result := []bean.BenchmarkEntity{}

	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "BM") {
			match := re.FindStringSubmatch(line)
			//fmt.Println("case:", match[1])
			//fmt.Println("time:", match[2])
			//fmt.Println("cpu:", match[3])
			//fmt.Println("iter:", match[4])
			executeTime, err := strconv.ParseFloat(match[2], 64)
			if err != nil {
				debug.PrintStack()
				fmt.Println(err)
			}
			cpu, err := strconv.ParseFloat(match[3], 64)
			if err != nil {
				debug.PrintStack()
				fmt.Println(err)
			}
			iterations, err := strconv.ParseInt(match[4], 0, 64)
			if err != nil {
				debug.PrintStack()
				fmt.Println(err)
			}
			result = append(result, bean.BenchmarkEntity{
				BaseEntity: bean.BaseEntity{
					Id:         unique_snowflake.Generate(),
					CreateTime: time.Now(),
					UpdateTime: time.Now(),
				},
				Testcase:    match[1],
				ExecuteTime: executeTime,
				Cpu:         cpu,
				Iterations:  iterations,
				RefTestId:   refTestId,
			})
		}
	}
	return result
}
